package md.mru.frontend.convertors;

import md.mru.core.dtos.BaseDto;

import javax.faces.component.UIComponent;
import javax.faces.component.UISelectItem;
import javax.faces.component.UISelectOne;
import javax.faces.component.html.HtmlSelectManyCheckbox;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import java.util.List;

@FacesConverter("genericMappingConverter")
public class GenericMappingConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
        if (value != null && !value.isEmpty()) {
            if (uiComponent instanceof UISelectOne || uiComponent instanceof HtmlSelectManyCheckbox) {
                for (UIComponent child : uiComponent.getChildren()) {
                    if (child instanceof UISelectItem) {
                        List<? extends BaseDto> list = (List<? extends BaseDto>) ((UISelectItem) child).getValue();
                        if (list != null) {
                            for (BaseDto gje : list) {
                                try {

                                    if (gje != null && gje.getId() != 0 && gje.getId() == Long.valueOf(value)) {
                                        return gje;
                                    }
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                    return null;
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value != null && value instanceof BaseDto) {
            return "" + ((BaseDto) value).getId();
        }
        return null;
    }
}
